
#include "MainDocument.h"
#include "MainView.h"
#include "FontsetNotebook.h"

IMPLEMENT_DYNAMIC_CLASS( MainDocument, wxDocument )

MainDocument::MainDocument(void)
{
    wxLogTrace( wxTraceMask(), wxT( "MainDocument::MainDocument" ) );
}

bool MainDocument::OnSaveDocument( const wxString& filename )
{
    wxLogTrace( wxTraceMask(), wxT( "MainDocument::OnSaveDocument" ) );
    do
    {
        MainView* view = (MainView*)GetFirstView();
        if ( !view )
            break;

        // Save the notebook:
        FontsetNotebook* notebook = view->GetNotebook();
        if ( !notebook )
            break;

        if ( !notebook->SaveFile( filename ) )
        {
            return false;
        }

        // Set the modified state to false:
        Modify( false );

    } while ( false );

    return true;
}

bool MainDocument::OnOpenDocument( const wxString& filename )
{
    wxLogTrace( wxTraceMask(), wxT( "MainDocument::OnOpenDocument" ) );
    do
    {
        MainView* view = (MainView*)GetFirstView();
        if ( !view )
            break;

        // Load the notebook:
        FontsetNotebook* notebook = view->GetNotebook();
        if ( !notebook )
            break;

        if ( !notebook->LoadFile( filename ) )
        {
            return false;
        }

        // Set the modified state to false:
        SetFilename( filename, true );
        Modify( false );
        UpdateAllViews();

    } while ( false );

    return true;
}

bool MainDocument::OnNewDocument()
{
    wxLogTrace( wxTraceMask(), wxT( "MainDocument::OnNewDocument" ) );
    //return DeleteAllViews();
    bool success = wxDocument::OnNewDocument();
    //bool success = true;
    if ( success )
    {
        MainView* view = (MainView*)GetFirstView();
        if ( view && view->GetNotebook() )
        {
            view->GetNotebook()->Reset();
        }
    }
    return success;
}

bool MainDocument::OnCloseDocument()
{
    wxLogTrace( wxTraceMask(), wxT( "MainDocument::OnCloseDocument" ) );
    return wxDocument::OnCloseDocument();
}

bool MainDocument::IsModified() const
{
    bool isMod = wxDocument::IsModified();
    MainView* view = (MainView*)GetFirstView();
    if ( view && view->GetNotebook() )
    {
        isMod |= view->GetNotebook()->IsModified();
    }
    return isMod;
}

void MainDocument::Modify( bool mod )
{
    MainView* view = (MainView*)GetFirstView();
    wxDocument::Modify( mod );
    if ( !mod && view && view->GetNotebook() )
    {
        view->GetNotebook()->Modify( false );
    }
}
